<?php
//http客户端易用

namespace App\Services\Common;

class HttpClientEasy
{

    /**
     * 客户端get请求
     * @param $url
     * @param $useAppToken
     * @param $data
     * @return false|mixed
     */
    public static function clientGet($url, $headers = [], $data = [])
    {
        //将$data拼接到url后面
        if ($data) {
            $url .= '?'.http_build_query($data);
        }
        $client = new \GuzzleHttp\Client();
        $baseHeaders = [
            'Content-Type' => 'application/json; charset=utf-8',
        ];
        $headers = array_merge($baseHeaders, $headers);
        try {
            $result = $client->get($url, [
                    'headers' => $headers,
                    'json'    => $data,
                ]
            );
            $res = $result->getBody()->getContents();
        } catch (\Exception $e) {
            $response = $e->getResponse();
            $res = $response->getBody()->getContents();
        }
        if (!$res) {
            return false;
        }

        return json_decode($res, true);
    }


    /**
     * 客户端post请求
     * @param $url
     * @param $useAppToken
     * @param $data
     * @return false|mixed
     */
    public static function clientPost($url, $headers = [], $data = [])
    {
        $client = new \GuzzleHttp\Client();
        $baseHeaders = [
            'Content-Type' => 'application/json; charset=utf-8',
        ];
        $headers = array_merge($baseHeaders, $headers);
        try {
            $result = $client->post($url, [
                    'headers' => $headers,
                    'json'    => $data,
                ]
            );
            $res = $result->getBody()->getContents();
        } catch (\Exception $e) {
            $response = $e->getResponse();
            $res = $response->getBody()->getContents();
        }
        if (!$res) {
            return false;
        }

        return json_decode($res, true);
    }


}